package com.mrd.gtimp.fix;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Service;

import com.mrd.exception.QueryException;
import com.mrd.gtimp.base.service.SystemValueBiz;
import com.mrd.gtimp.business.entity.Commodity;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.entity.HgData;
import com.mrd.gtimp.business.service.HgDataBiz;
import com.mrd.gtimpframe.service.CacheService;

/**
 * Created by winaya on 2017/1/6.
 * 
 * @modify han 优化，实现类初始化的时候自动初始化数据，免去每次初始化数据
 */
@Service
@ConditionalOnClass(CacheService.class)
public class ChnToCodeFix implements InitializingBean {
  @Autowired
  CacheService cacheService;

  /**
   * 单位映射Map<中文，编码>
   */
  private Map<String, String> units;
  private Map<String, List<HgData>> hgdataMap = null;
  @Resource
  private HgDataBiz hgDataBiz;
  @Resource
  private SystemValueBiz systemValueBiz;

  public void chnToCode(Declaration declaration) {
    if (declaration == null) {
      return;
    }
    declarationFix(declaration);
    countryFix(declaration);
    commondityFix(declaration.getCommodities());
  }

  private void initCodeMap() {
    if (hgdataMap == null) {
      try {
        hgdataMap = hgDataBiz.findCurrencySystem().get("data");
      } catch (QueryException e) {
        e.printStackTrace();
        hgdataMap = null;
      }
    }
  }

  private void declarationFix(Declaration declaration) {
    if (StringUtils.isNotEmpty(declaration.getTransport_mode())
        && StringUtils.isEmpty(declaration.getTransport_mode_code())) {
      declaration.setTransport_mode_code(
          cacheService.hgdataCover(hgdataMap, "HGD_A", declaration.getTransport_mode()));
    }
  }

  /**
   * 这里修复的有 运抵国、贸易国、指运港
   * 
   * @param declaration
   */
  private void countryFix(Declaration declaration) {
    String arrivedCountry = declaration.getArrived_country();
    if (StringUtils.isEmpty(declaration.getArrived_country_code())
        && StringUtils.isNotEmpty(arrivedCountry)) {
      declaration
          .setArrived_country_code(cacheService.hgdataCover(hgdataMap, "HGD_0", arrivedCountry));
    }

    String arrivePort = declaration.getArrived_port();
    if (StringUtils.isEmpty(declaration.getArrived_port_code())
        && StringUtils.isNotEmpty(arrivePort)) {
      declaration.setArrived_port_code(cacheService.hgdataCover(hgdataMap, "HGD_0", arrivePort));
    }

    String tradingCountry = declaration.getTrading_country();
    if (StringUtils.isEmpty(declaration.getTrading_country_code())
        && StringUtils.isNotEmpty(tradingCountry)) {
      declaration
          .setTrading_country_code(cacheService.hgdataCover(hgdataMap, "HGD_0", tradingCountry));
    }
  }

  private void commondityFix(List<Commodity> commodities) {
    if (CollectionUtils.isEmpty(commodities)) {
      return;
    }
    commodities.forEach(c -> {
      // 计价单位
      if (StringUtils.isNotEmpty(c.getUnit()) && StringUtils.isEmpty(c.getUnitCode())) {
        c.setUnitCode(unit(c.getUnit()));
      }
      // 第一单位
      if (StringUtils.isNotEmpty(c.getLegal_unit()) && StringUtils.isEmpty(c.getLegalUnitCode())) {
        c.setLegalUnitCode(unit(c.getLegal_unit()));
      }
      // 第二单位
      if (StringUtils.isNotEmpty(c.getSecond_unit())
          && StringUtils.isEmpty(c.getSecondUnitCode())) {
        c.setSecondUnitCode(unit(c.getSecond_unit()));
      }
      // 币种
      if (StringUtils.isNotEmpty(c.getCurrency()) && StringUtils.isEmpty(c.getCurrencyCode())) {
        c.setCurrencyCode(cacheService.hgdataCover(hgdataMap, "HGD_1", c.getCurrency()));
      }
      // 币种
      if (StringUtils.isNotEmpty(c.getLevymode()) && StringUtils.isEmpty(c.getLevyModeCode())) {
        c.setLevyModeCode(cacheService.hgdataCover(hgdataMap, "HGD_5", c.getLevymode()));
      }
    });
  }

  public void freightFix(Declaration declaration) {
    if (declaration == null) {
      return;
    }
    initCodeMap();
    String freight1 = declaration.getFreight1();
    if (StringUtils.isNotEmpty(freight1)) {
      declaration.setFreight1Code("总价".equals(freight1) ? "3" : "1");
      declaration
          .setFreight3Code(cacheService.hgdataCover(hgdataMap, "HGD_1", declaration.getFreight3()));
    }

    String premium1 = declaration.getPremium1();
    if (StringUtils.isNotEmpty(premium1)) {
      declaration.setPremium1Code("总价".equals(freight1) ? "3" : "1");
      declaration
          .setPremium3Code(cacheService.hgdataCover(hgdataMap, "HGD_1", declaration.getPremium3()));
    }

    String otherfee1 = declaration.getOtherfee1();
    if (StringUtils.isNotEmpty(otherfee1)) {
      declaration.setOtherfee1Code("总价".equals(freight1) ? "3" : "1");
      declaration.setOtherfee3Code(
          cacheService.hgdataCover(hgdataMap, "HGD_1", declaration.getPremium3()));
    }
  }

  /**
   * 单位转换
   */
  public String unit(String source) {
    if (units == null) {
      try {
        String[][] unitArray = systemValueBiz.findUnitsOfMeasurement();
        units = new HashMap<>();
        for (String[] strings : unitArray) {
          units.put(strings[0], strings[1]);
        }
      } catch (QueryException e) {
        return null;
      }
    }
    return units.get(source);
  }

  @Override
  /**
   * 优化 在bean初始化的时候初始化数据
   */
  public void afterPropertiesSet() throws Exception {
    initCodeMap();
  }
}
